/**
 * New DeviceOne File
 */
var d1 = require('deviceone')
var app = require('config/app')
var log = require('util/log')
var network = d1.sm('do_Network')
var storage = require('util/storage')
var constant = require('config/constant')
var server = require('config/server')
var promise = require('lib/promise')
var notify = d1.sm('do_Notification')
var App = d1.sm('do_App')
// 基础请求地址
var SERVER_URL = app.url[app.env].SERVER_URL

function generateHttpObject(isApp) {
	if (isApp) {
		return d1.mm("do_Http", (+new Date).toString(), "app");
	} else {
		return d1.mm("do_Http");
	}
}

/**
 * 组装url地址
 * 
 * @returns
 */
function generateHttpUrl(server, data, append) {
	var service = server.service
	var controller = server.controller
	var action = server.action
	var method = server.type

	var dataPostfix = ''
	var appendPostfix = ''
	var postfixMethod = [ 'GET', 'DELETE' ]
	if (method && data && Object.keys(data).length > 0
			&& postfixMethod.indexOf(method) >= 0) {
		var postfixArray = []

		Object.entries(data).each(function(index, item) {
			if (item && item.value !== '' && item.value !== undefined) {
				postfixArray.push(item.key + '=' + item.value)
			}
			var postfix = postfixArray.join('&')
			if (postfix.length > 0) {
				dataPostfix = '?' + postfix
			}
		})
	}

	// 生成追加数据
	// 排除空数组/空字符
	if (append && append.length) {
		appendPostfix = '/'
				+ ((append instanceof Array) ? append.join('/') : append)
	}

	// 排除空action
	action = action ? ('/' + action) : ''

	var url = SERVER_URL + '/' + service + '/api/' + controller + action
			+ appendPostfix + dataPostfix;

	return encodeURI(url)
}

module.exports.send = function(options, isApp) {
	var process = new promise.Promise()
	// 初始化http对象
	var _http = generateHttpObject(isApp)
	var server = options.server // 服务配置对象
	var data = options.data // 数据传递对象
	var append = options.append // 附加数据
	var method = server.type
	var page = options.page

	if (page) {
		log.info(page.getConfig())
		data.page = page.getConfig().page
		data.size = page.getConfig().size
	}
	var url = generateHttpUrl(server, data, append);
	// 配置通讯参数
	_http.url = url
	_http.contentType = 'application/json'
	_http.body = JSON.stringify(data);
	_http.method = method;
	_http.timeout = 10000;

	var token = storage.getItem(constant.user.token)
	if (token) {
		_http.setRequestHeader('X-UserToken', token)
	}

	// 成功回调处理
	_http.on("success", function(result) {
		if (result.success) {
			if (options.success) {
				try {
					if (page && typeof page === 'object') {
						page.totle = result.object.totalPages
					}
					options.success.call(options.scope, result.object)
					process.done()
				} catch (ex) {
					log.info(ex.message)
					process.done()
				}
			}
		} else {
			if (options.error) {
				try {
					options.error.call(options.scope, {
						reason : result.reason,
						errors : result.errors
					})
					process.done()
				} catch (ex) {
					log.info(ex.message)
					process.done()
				}
			}
		}
	});

	// 失败回调处理
	_http.on("fail", function(result) {
		if (options.error) {
			try {
				options.error.call(options.scope, {
					reason : result.reason,
					errors : result.errors
				})
				process.done()
			} catch (ex) {
				process.done()
			}
		}

		// token验证失败重新登录
		if (result.status === 403) {
			notify.toast("用户身份验证超时，请重新登录")
			storage.clearItem(constant.user.id)
			storage.clearItem(constant.user.token)
			storage.clearItem(constant.user.data)

			try {
				App.closePageToID("", "", "app/login");
			} catch (ex) {
				App.openPage({
					source : "source://view/app/login.ui",
					id : "app/login"
				});
			}
		}

		if (result.status === 408) {
			notify.toast("连接超时，请稍后再试")
		}
	});

	// 通讯完成回调
	_http.on("result", function(data) {
		log.info(url, data)
		if (options.callback) {
			try {
				options.callback.call(options.scope, data)
				process.done()
			} catch (ex) {
				process.done()
			}
		}
	});

	// 发送通讯请求
	_http.request();
	return process
};

module.exports.upload = function(options) {
	log.info(options)
	var _http = generateHttpObject()
	var data = options.data // 数据传递对象
	var append = options.append // 附加数据
	var file = options.file[0] // 附加数据
	var method = server.file.upload.type
	var url = generateHttpUrl(server.file.upload, data, append);
	// 配置通讯参数
	_http.url = url
	_http.contentType = "multipart/form-data";
	_http.body = JSON.stringify(data);
	_http.method = method;
	_http.timeout = 1000 * 60 * 60;

	var token = storage.getItem(constant.user.token)
	if (token) {
		_http.setRequestHeader('X-UserToken', token)
	}

	// 成功回调处理
	_http.on("success", function(result) {
		if (result.success) {
			if (options.success) {
				try {
					options.success.call(options.scope, result.object)
				} catch (ex) {
					log.info(ex.message)
				}
			}
		} else {
			if (options.error) {
				try {
					options.error.call(options.scope, {
						reason : result.reason,
						errors : result.errors
					})
				} catch (ex) {
					log.info(ex.message)
				}
			}
		}
	});

	// 失败回调处理
	_http.on("fail", function(result) {
		if (options.error) {
			try {
				options.error.call(options.scope, {
					reason : result.reason,
					errors : result.errors
				})
			} catch (ex) {

			}
		}
	});

	// 通讯完成回调
	_http.on("result", function(data) {
		log.info(url, data)
		if (options.callback) {
			try {
				options.callback.call(options.scope, data)
			} catch (ex) {

			}
		}
	});

	// 发送通讯请求
	_http.upload(file);
};

/**
 * 检测网络状态
 */
module.exports.getStatus = function() {
	return network.getStatus() !== 'none'
}